package grape.wx.service.mp.impl.handler;

import grape.wx.service.mp.MpProperties;
import grape.wx.service.mp.api.handler.IMpUnsubscribeHandler;
import grape.wx.service.mp.user.api.IMpUserService;
import grape.wx.service.mp.user.po.MpUser;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by yangwei
 * Created at 2020/7/21 18:44
 */
@Service
public class MpUnsubscribeHandlerImpl implements IMpUnsubscribeHandler {

    @Autowired
    private IMpUserService iMpUserService;
    @Autowired
    private MpProperties mpProperties;
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        MpProperties.MpConfig mpConfig = mpProperties.abtainConfigByAppCodeOrAppId(WxMpConfigStorageHolder.get());
        MpUser byOpenidAndAppCode = iMpUserService.getByOpenidAndAppCode(wxMessage.getFromUser(), mpConfig.getAppCode());
        if (byOpenidAndAppCode != null) {
            MpUser mpUser = new MpUser();
            mpUser.setId(byOpenidAndAppCode.getId());
            mpUser.setIsSubscribe(false);
            iMpUserService.updateById(mpUser);
        }
        return null;
    }
}
